package com.jjiang.bbmall.order.web;

import com.jjiang.bbmall.order.enume.SubmitStatusEnum;
import com.jjiang.bbmall.order.exception.NoStockException;
import com.jjiang.bbmall.order.service.OrderService;
import com.jjiang.bbmall.order.vo.OrderConfirmVo;
import com.jjiang.bbmall.order.vo.OrderSubmitVo;
import com.jjiang.bbmall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Objects;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) {
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", orderConfirmVo);
        return "confirm";
    }

    /**
     * 提交，下单
     *
     * @param orderSubmitVo 提交的信息
     * @return 页面
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        // 进行下单；创建订单；验证令牌；验证价格；锁定库存
        // 如果成功，则到支付选择页面
        // 如果失败，则需要返回下单页面
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(orderSubmitVo);
            if (Objects.equals(responseVo.getCode(), SubmitStatusEnum.SUCCESS.getCode())) {
                // 下单成功
                model.addAttribute("submitOrderResp", responseVo);
                return "pay";
            } else {
                // 下单失败
                String msg = "下单失败：";
                switch (responseVo.getCode()) {
                    case 1:
                        msg += SubmitStatusEnum.TOKEN_ERROR.getMsg();
                        break;
                    case 2:
                        msg += SubmitStatusEnum.PRICE_ERROR.getMsg();
                        break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://127.0.0.1:9000/toTrade";
            }
        } catch (NoStockException exception) {
            redirectAttributes.addFlashAttribute("msg", SubmitStatusEnum.NO_STOCK_ERROR.getMsg());
            return "redirect:http://127.0.0.1:9000/toTrade";
        }
    }
}
